import React, { useState } from 'react'
import styles from './index.module.scss'
import { memo } from 'react'
import NavBar from '../../components/NavBar'
import Input from '../../components/Input'
import * as Yup from 'yup'
import { Toast } from 'antd-mobile'
import { useFormik } from 'formik'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { codeSend, LoginUser } from './store/action'
import { useHistory, useLocation } from 'react-router'
export default memo(function Login() {
  const dispatch = useDispatch()
  const { replace } = useHistory()
  const location = useLocation<{ from: string }>()
  // 表单
  const form = useFormik({
    initialValues: {
      mobile: '13900001111',
      code: '246810',
    },
    async onSubmit(val) {
      await dispatch(
        LoginUser({
          mobile: val.mobile,
          code: val.code,
        })
      )
      Toast.success('登陆成功！')
      const pathname = location.state ? location.state.from : '/home/profile'
      replace(pathname)
    },
    // 表单验证
    validationSchema: Yup.object().shape({
      // 手机号验证规则
      mobile: Yup.string()
        .required('请输入手机号')
        .matches(/^1[3456789]\d{9}$/, '手机号格式错误'),

      // 手机验证码验证规则
      code: Yup.string()
        .required('请输入验证码')
        .matches(/^\d{6}$/, '验证码6个数字'),
    }),
  })
  // 点击获取验证码
  const onExtraClick = async () => {
    if (time > 0) return
    if (/^1[3456789]\d{9}$/.test(form.values.mobile)) {
      try {
        await dispatch(codeSend(form.values.mobile))
        Toast.success('获取验证码成功！', 2)
        setTime(60)
        let timer = setInterval(
          () =>
            setTime((time) => {
              if (time === 1) clearInterval(timer)
              return time - 1
            }),
          1000
        )
      } catch (err: any) {
        Toast.fail(err.response.data.message, 2)
      }
    } else {
      form.setTouched({
        mobile: true,
      })
    }
  }

  const [time, setTime] = useState(0)
  return (
    <div className={styles.root}>
      <div className={styles.root}>
        <NavBar>{'登录'}</NavBar>
        <div className="content">
          {/* 标题 */}
          <h3>短信登录</h3>
          <form onSubmit={form.handleSubmit}>
            {/* 手机号输入框 */}
            <div className="input-item">
              <div className="input-box">
                <Input
                  className="input"
                  name="mobile"
                  placeholder="请输入手机号"
                  maxLength={11}
                  autoComplete="off"
                  value={form.values.mobile}
                  onChange={form.handleChange}
                />
              </div>
              {form.errors.mobile && form.touched.mobile && (
                <div className="validate">{form.errors.mobile}</div>
              )}
            </div>

            {/* 短信验证码输入框 */}
            <div className="input-item">
              <div className="input-box">
                <Input
                  placeholder="请输入验证码"
                  maxLength={6}
                  autoComplete="off"
                  name="code"
                  extra={time === 0 ? '获取验证码' : time + '秒后获取'}
                  value={form.values.code}
                  onChange={form.handleChange}
                  onExtraClick={onExtraClick}
                />
              </div>
              {form.errors.code && form.touched.code && (
                <div className="validate">{form.errors.code}</div>
              )}
            </div>

            {/* 登录按钮 */}
            <button
              type="submit"
              className={classNames(
                'login-btn',
                form.isValid ? '' : 'disabled'
              )}
              disabled={!form.isValid}
            >
              登录
            </button>
          </form>
        </div>
      </div>
    </div>
  )
})
